<?php

namespace fakis\treegrid;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\ActiveQueryInterface;
use yii\helpers\Html;
use yii\helpers\Inflector;

/**
 * Column is the base class of all [[TreeGrid]] column classes.
 * The code was based in: https://github.com/yiisoft/yii2/blob/master/framework/grid/DataColumn.php
 */
class DataColumn extends \yii\grid\DataColumn
{
    /**
     * Renders the header cell content.
     * The default implementation simply renders [[header]].
     * This method may be overridden to customize the rendering of the header cell.
     * @return string the rendering result
     */
    protected function renderHeaderCellContent()
    {
        if ($this->header !== null || $this->label === null && $this->attribute === null) {
            return trim($this->header) !== '' ? $this->header : $this->grid->emptyCell;
        }

        $dataProvider = $this->grid->dataProvider;

        if ($this->label === null) {
            if ($dataProvider instanceof ActiveDataProvider && $dataProvider->query instanceof ActiveQueryInterface) {
                /* @var $model Model */
                $model = new $dataProvider->query->modelClass;
                $label = $model->getAttributeLabel($this->attribute);
            } else {
                $models = $dataProvider->getModels();
                if (($model = reset($models)) instanceof Model) {
                    /* @var $model Model */
                    $label = $model->getAttributeLabel($this->attribute);
                } else {
                    $label = Inflector::camel2words($this->attribute);
                }
            }
        } else {
            $label = $this->label;
        }

        return $this->encodeLabel ? Html::encode($label) : $label;
    }
}
